package project.background.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import fld.background.dto.UserDto;
import fld.background.entity.Role;
import fld.background.entity.User;
import fld.background.service.DicItemService;
import fld.background.service.RoleService;
import fld.background.service.UserService;
import fld.background.system.service.impl.BaseServiceImpl;
import fld.project.entity.Company;
import fld.utils.Common;
import fld.utils.DataGrid;
import fld.utils.MD5;
import fld.utils.Page;
import fld.utils.Result;
import project.background.utils.UserUtils;

/**
 * 企业账号
 * @author yc
 * 2018年12月31日
 */
@Service
public class CompanyUserService extends BaseServiceImpl<User,Long>{
	
	@Autowired
	private RoleService roleService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private DicItemService dicItemService;
	@Autowired
	private UserService userService;
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	/**
	 * 查询全部
	 * @param tmap
	 * @return
	 * @author yc
	 * @date 2018年12月7日
	 */
	public Result queryAll(Map<String,Object> tmap){
		if("".equals(Common.nullToEmpty(tmap.get("companyId")))) {
			tmap.put("companyId", userService.getCurUser().getCompanyId());
		}else {
			tmap.put("companyId", Long.parseLong(tmap.get("companyId").toString()));
		}
		List<User> list = query(UserDto.class, tmap);
		List<Map<String,Object>> res = new ArrayList<Map<String,Object>>();
		for (User t : list) {
			Map<String,Object> m = new HashMap<String,Object>();
			m.put("text", t.getId());
			m.put("name", t.getName());
			res.add(m);
		}
		return new Result(true,"",res); 
	}
	
	/**
	 * 查询分页
	 * @param tmap
	 * @return
	 */
	public DataGrid grid(Map<String,Object> tmap){
		if(!"".equals(Common.nullToEmpty(tmap.get("userName")))){
			tmap.put("userName","%"+tmap.get("userName")+"%");
		}
		if(!"".equals(Common.nullToEmpty(tmap.get("name")))){
			tmap.put("name","%"+tmap.get("name")+"%");
		}
		if(UserUtils.isCompanyUser(userService.getCurUser())) {
			tmap.put("companyId", userService.getCurUser().getCompanyId());
		}else if(UserUtils.isRootUser(userService.getCurUser())) {
			if(!"".equals(Common.nullToEmpty(tmap.get("companyId")))) {
				tmap.put("companyId", Long.parseLong(tmap.get("companyId").toString()));
			}
		}else {
			tmap.put("companyId", -1L);
		}
		Page<User> page = queryForPage(UserDto.class, tmap);
		List<Map<String,Object>> rows = new ArrayList<Map<String,Object>>();
		List<User> res = page.getRows();
		for (User t : res) {
			Map<String,Object> m = new HashMap<String,Object>();
			m.put("id", t.getId());
			m.put("userName", t.getUserName());
			m.put("createTime", null == t.getCreateTime()?"":sdf.format(t.getCreateTime()));
			m.put("name", t.getName());
			m.put("state", t.getState());
			m.put("stateName", dicItemService.convertDicItem("STATE", Common.nullToEmpty(t.getState())));
			m.put("type", t.getType());
			m.put("typeName", dicItemService.convertDicItem("USERTYPE", Common.nullToEmpty(t.getType())));
			m.put("companyId", t.getCompanyId());
			m.put("head", t.getHead());
			List<Role> roles = t.getRoles();
			StringBuilder roleName = new StringBuilder();
			for (Role role : roles) {
				roleName.append(role.getRoleName()+",");
			}
			m.put("roleName", "".equals(roleName.toString())?"":roleName.toString().substring(0, roleName.toString().length()-1));
			rows.add(m);
		}
		DataGrid dg = new DataGrid();
		dg.setTotal(page.getTotal());
		dg.setRows(rows);
		dg.setTotalPage(page.getPageCount());
		return dg;
	}
	
	/**
	 * 获取详情
	 * @param id
	 * @return
	 */
	public Map<String,Object> getInfo(Long id){
		User t = getDao().get(id);
		Map<String,Object> map = new HashMap<String,Object>();
		if(t != null){
			map.put("id", t.getId());
			map.put("createTime", null == t.getCreateTime()?"":sdf.format(t.getCreateTime()));
			map.put("userName", t.getUserName());
			map.put("name", t.getName());
			map.put("phone", t.getPhone());
			map.put("address", t.getAddress());
			map.put("email", t.getEmail());
			map.put("state", t.getState());
			map.put("type", t.getType());
			map.put("companyId", t.getCompanyId());
			map.put("head", t.getHead());
			map.put("companyName", null);
			if(null != t.getCompanyId()) {
				Company c = companyService.getDao().get(t.getCompanyId());
				if(null != c) {
					map.put("companyName", c.getName());
				}
			}
			List<Role> roles = t.getRoles();
			for (Role role : roles) {
				map.put("roleIds", role.getId());
			}
			
		}
		return map;
	}
	
	/**
	 * 新增/修改
	 * @param t
	 */
	public Result saveObj(User t,String roleIds) {
		Long companyId = userService.getCurUser().getCompanyId();
		if(null  == companyId) {
			return new Result(false,"没有操作权限");
		}else {
			t.setCompanyId(companyId);
		}
		String[] roleIdArray = Common.nullToEmpty(roleIds).split(",");
		List<Role> list = new ArrayList<Role>();
		for (String roleId : roleIdArray) {
			Role r = roleService.getDao().get(Long.parseLong(roleId));
			list.add(r);
		}
		
		User u = queryByUserName(t.getUserName());
		
		if("".equals(Common.nullToEmpty(t.getId()))){
			//新增
			if(null != u)
				return new Result(false,"该用户名已存在");
			if("".equals(Common.nullToEmpty(t.getPassWord()))){
				t.setPassWord(MD5.GetMD5Code("123456"));//默认密码为123456
			}else{
				if(t.getPassWord().length()<6){
					return new Result(false,"密码长度不能低于6位");
				}else {
					t.setPassWord(MD5.GetMD5Code(t.getPassWord()));
				}
			}
			
			t.setThemePc("bootstrap");
			t.setRoles(list);
			getDao().saveOrUpdate(t);
		}else{
			if(null != u && !Common.nullToEmpty(u.getId()).equals(Common.nullToEmpty(t.getId())))
				return new Result(false,"该用户名已存在");
			
			User user = getDao().get(t.getId());
			user.setUserName(t.getUserName());
			if(!"".equals(t.getPassWord())){
				if(t.getPassWord().length()<6){
					return new Result(false,"密码长度不能低于6位");
				}else {
					user.setPassWord(MD5.GetMD5Code(t.getPassWord()));
				}
			}
			user.setName(t.getName());
			user.setPhone(t.getPhone());
			user.setAddress(t.getAddress());
			user.setEmail(t.getEmail());
			user.setType(t.getType());
			user.setState(t.getState());
			user.setHead(t.getHead());
			user.setRoles(list);
			getDao().saveOrUpdate(user);
		}
		return new Result(true);
	}
	
	/**
	 * 根据id删除
	 * @param id
	 * @return
	 */
	public Result deleteById(Long id){
		User t = getDao().get(id);
		if(null != t) {
			t.setIsdeleted(true);
			save(t);
		}
		return new Result(true);
	}
	
	/**
	 * 校验用户名是否已存在
	 * @param userName
	 * @return
	 */
	public User queryByUserName(String userName){
		userName = Common.nullToEmpty(userName);
		return getDao().getByHQL("from User where userName = (?) and isdeleted = 0", userName);
	}
	
}
